import httpsUtils from 'https.js';
import myUtils from 'util.js';
const app = getApp();


var uploadTimes = 0;
var ossImgPath = [];
var uploadCount = 0;
var ossImgPathBatch = [];
module.exports = {
  /**
   * token:用户token
   * loginType:跳转页面，1-跳转我的页面，2-跳转发布页面
   * callback:回调函数
   */
  getUserInfoByToken: function (token, loginType, callback) {
    if (myUtils.isBlank(token)) {
      wx.navigateTo({
        url: '../wxLogin/wxLogin?type=' + loginType ,
      })
    } else {
      wx.request({
        url: app.globalData._url + '/login/selectLoginUser',
        data: {},
        method: 'GET',
        header: {
          'content-type': 'application/json;charset=UTF-8',
          'x-client-token': token
        },
        success: function (res) {
          if (res.data.code == 'SUCCESS') {
            wx.setStorageSync('userInfo', res.data.data);
            wx.setStorageSync('utoken', res.data.data.token);
            typeof callback === 'function' && callback(res.data);
          } else {
            wx.navigateTo({
              url: '../wxLogin/wxLogin?type=' + loginType ,
            })
          }
        },
        fail: function () {
        },
        complete: function () {
        }
      })
    }
  },

  /**
   * 上传文件
   * srcImgPath：上传文件地址
   * isFirst: 是否第一次
   * callback:回调函数
   */
  myUploadFile: function (srcImgPath,isFirst, callback) {
    var that = this;
    if(isFirst){
      ossImgPath = []
    }
    wx.uploadFile({
      url: app.globalData._url + '/oss/upload',
      filePath: srcImgPath[uploadTimes],
      name: 'file',
      header: { "Content-Type": "multipart/form-data" },
      success: function (res) {
        let jsonData = JSON.parse(res.data);
        if (jsonData.code!= undefined && jsonData.code == "SUCCESS"){
          ossImgPath.push(jsonData.data);
        }
      },
      fail: function () {
        console.log('上传失败')
      },
      complete: function () {
        uploadTimes++;
        if (uploadTimes < srcImgPath.length) {
          that.myUploadFile(srcImgPath,false, callback)
        } else {
          uploadTimes = 0;
          typeof callback === 'function' && callback(ossImgPath);
        }
      }
    })
  },

  /**
   * 批量上传文件
   * srcImgPath：上传文件地址
   * isFirst : 是否第一次
   * callback:回调函数
   */
  myUploadFileBatch: function (srcImgPathBatch, isFirst,callback) {
    var that = this;
    if (isFirst) {
      ossImgPathBatch = []
    }
    that.myUploadFile(srcImgPathBatch[uploadCount], true, function (res) {
      uploadCount++;
      ossImgPathBatch.push(res);
      if (uploadCount == srcImgPathBatch.length) {
        uploadCount = 0;
        typeof callback === 'function' && callback(ossImgPathBatch);
      } else {
        that.myUploadFileBatch(srcImgPathBatch, false, callback);
      }
    });
  }
}